package com.bdqn.t296.syn;

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class UnsafeBuyTicket {//不安全的买票:线程不安全，不同的人拿到同一张票、出现负数

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "明明").start();
        new Thread(buyTicket, "红红").start();
        new Thread(buyTicket, "黄牛").start();

    }
}

class BuyTicket implements Runnable {//线程类
    //票
    private int ticketNums = 10;
    boolean flag = true;//外部停止方式

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        //模拟延迟
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
    }
}
